<?php

namespace App\Admin\Controllers;

use App\Miya\Models\Module;
use App\Miya\Models\ModuleType;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;

class ModuleTypeController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '模块属性';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ModuleType());
        $grid->model()->has('module')
            ->with(['module'])->orderBy('id', 'DESC');

        $grid->column('id', '序号');
        $grid->column('module_id', '所属模块')->display(function () {
            return $this->module->name;
        })->label();
        $grid->column('name', '属性名')->label();
        $grid->column('values', '属性可选值')->display(function () {
            return '点击查看';
        })->modal('属性可选值', function ($model) {
            $data = collect($model->values)->map(function ($values) {
                return array_values($values);
            })->toArray();
            return new Table(['属性值', 'Hash值'], $data);
        });

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ModuleType());

        $form->select('module_id', '模块')
            ->options(Module::pluck('name', 'id'))->rules(['required']);
        $form->text('name', '属性名')->rules(['required']);
        if ($form->isCreating()) {
            $form->table('values', '属性可选值', function ($table) {
                $table->text('value', '属性值')->rules(['required']);
            });
        } else {
            $form->table('values', '属性可选值', function ($table) {
                $table->text('value', '属性值')->rules(['required']);
                $table->hidden('hash', 'Hash值');
            });
        }

        return $form;
    }
}
